﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Text.Json;

namespace ExcelSugar.Core.Converter
{
    public class JsonCellValueConver : DefaultCellValueConverter, ICellValueConverter
    {
        public new object? CellToProperty(string cellValue, PropertyInfo propertyInfo )
        {
            if (propertyInfo.GetCustomAttribute<SugarHeadAttribute>()?.IsJson == true)
            {
                if (!string.IsNullOrEmpty(cellValue))
                {
                    string value = cellValue.TrimStart("\"".ToCharArray()).TrimEnd("\"".ToCharArray());
                    var result = JsonSerializer.Deserialize(value, propertyInfo.PropertyType);
                    return result;
                }
                return null;
            }
            else
            {
                return base.CellToProperty(cellValue, propertyInfo);

            }
        }

        public new string PropertyToCell(object? propertyValue, PropertyInfo propertyInfo)
        {
            if (propertyInfo.GetCustomAttribute<SugarHeadAttribute>()?.IsJson == true)
            {
                var data = "";
                if (propertyValue is not null)
                {
                    return JsonSerializer.Serialize(propertyValue).TrimStart("\"".ToCharArray()).TrimEnd("\"".ToCharArray());
                }
                return data;
            }
            else
            {
                return base.PropertyToCell(propertyValue, propertyInfo);
            }

        }
    }
}
